//
//  LyzmlDLNAModule.m
//  libWeexLyzmlDLNA
//
//  Created by edz on 2020/3/31.
//  Copyright © 2020 coolanimals. All rights reserved.
//

#import "LyzmlDLNAModule.h"
#import "WXUtility.h"
#import "CLUPnPServer.h"
#import "CLUPnPRenderer.h"
#import "CLUPnPDevice.h"

@interface LyzmlDLNAModule ()<CLUPnPServerDelegate,CLUPnPResponseDelegate>{
    CLUPnPServer *upd;
    CLUPnPRenderer *render;
}
@property (nonatomic, strong) CLUPnPDevice *connectedDevice;
@end

@implementation LyzmlDLNAModule;

@synthesize weexInstance;

WX_EXPORT_METHOD(@selector(startSearch:));
WX_EXPORT_METHOD(@selector(stopSearch));
WX_EXPORT_METHOD(@selector(getSearchResult:));
WX_EXPORT_METHOD(@selector(playVideo:callback:));
WX_EXPORT_METHOD(@selector(stopVideo));

WXModuleKeepAliveCallback searchCallback;

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"====dealloc=====");
}

- (instancetype)init
{
    if (self = [super init]) {
        NSLog(@"====lyzmlDLNA init=====");
        upd = [CLUPnPServer shareServer];
        upd.delegate = self;
    }
    return self;
}

/**
 * 连接设备，初始化控制器render
 */
- (void)connectDevice:(NSString *)ip
{
    NSArray<CLUPnPDevice *> *deviceList = [upd getDeviceList];
    if(deviceList != nil && deviceList.count>0){
        for(int i=0;i<deviceList.count;i++){
            CLUPnPDevice *dev = deviceList[i];
            NSString *devIp = [dev.location host];
            if([ip isEqualToString:devIp]){
                self.connectedDevice = dev;
                render = [[CLUPnPRenderer alloc] initWithModel:self.connectedDevice];
                render.delegate = self;
            }
        }
    }else{
        self.connectedDevice = nil;
        render = nil;
    }
}

#pragma mark -
#pragma mark -- 搜索协议CLUPnPDeviceDelegate回调 --
- (void)upnpSearchChangeWithResults:(NSArray<CLUPnPDevice *> *)devices{
    NSMutableArray *dataArray = [NSMutableArray array];
    for(int i=0;i<devices.count;i++){
       CLUPnPDevice *dev = devices[i];
       NSMutableDictionary *devDic = [NSMutableDictionary dictionary];
       [devDic setObject:dev.friendlyName forKey:@"name"];
       [devDic setObject:[dev.location host] forKey:@"ip"];
       [dataArray addObject:devDic];
    }
    searchCallback(dataArray,YES);
}

- (void)upnpSearchErrorWithError:(NSError *)error{
    NSLog(@"====dlna search error==%@", error);
}

#pragma mark -
#pragma mark - 控制协议CLUPnPResponseDelegate回调-
- (void)upnpSetAVTransportURIResponse{
    [render play];
}

- (void)upnpGetTransportInfoResponse:(CLUPnPTransportInfo *)info{
    
}

#pragma mark -
#pragma mark - Export Method
//开始搜索，通过回调返回搜索结果
- (void)startSearch:(WXModuleKeepAliveCallback)callback
{
    if(callback){
        searchCallback = callback;
        [upd start];
    }else{
        NSLog(@"====lyzmlDLNA _startSearch cancel,no callback=====");
    }
}

//停止搜索
- (void)stopSearch
{
    [upd stop];
}

//主动获取搜索结果
- (void)getSearchResult:(WXModuleKeepAliveCallback)callback
{
    if(callback){
        NSArray<CLUPnPDevice *> *devices = [upd getDeviceList];
        NSMutableArray *dataArray = [NSMutableArray array];
        for(int i=0;i<devices.count;i++){
           CLUPnPDevice *dev = devices[i];
           NSMutableDictionary *devDic = [NSMutableDictionary dictionary];
           [devDic setObject:dev.friendlyName forKey:@"name"];
           [devDic setObject:[dev.location host] forKey:@"ip"];
           [dataArray addObject:devDic];
        }
        callback(dataArray,YES);
    }
}

//通过IP来连接设备，同时播放视频
- (void)playVideo:(NSMutableDictionary *)params callback:(WXModuleKeepAliveCallback)callback
{
    NSMutableDictionary *retDic = [NSMutableDictionary dictionary];
    NSString *ip = [params objectForKey:@"ip"];
    NSString *videoUrl = [params objectForKey:@"mediaURL"];
    
    if(ip != nil && videoUrl != nil){
        if(self.connectedDevice!=nil && [ip isEqualToString:self.connectedDevice.location.host]){
            //已连接
            [render setAVTransportURL:videoUrl];
        }else{
            //未连接或更换设备
            [self connectDevice:ip];
            [render setAVTransportURL:videoUrl];
        }
        [retDic setObject:@"0" forKey:@"code"];
        [retDic setObject:@"播放成功" forKey:@"desc"];
    }else{
        [retDic setObject:@"1" forKey:@"code"];
        [retDic setObject:@"参数错误" forKey:@"desc"];
    }
    if(callback){
        callback(retDic,YES);
    }
}

//停止播放
- (void)stopVideo
{
    if(render){
        [render stop];
    }
}
@end
